package com.estronger.shopmanage.utils;

import java.io.File;

import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;

public class MedialPlayerFunc implements OnPreparedListener {

	private MedialPlayerFunc() {

	}

	private static MedialPlayerFunc mInstance;
	private MediaPlayer mPlayer;
	private boolean isPlaying = false;

	public boolean getIsPlaying() {
		return isPlaying;
	}

	public void setPlaying(boolean b) {
		isPlaying = b;
	}

	private OnCompletionListener listener;

	public synchronized static MedialPlayerFunc getInstance() {
		if (mInstance == null)
			mInstance = new MedialPlayerFunc();
		return mInstance;
	}

	/**
	 * 开始播放
	 * 
	 * @param path
	 * @param listener
	 * @return
	 */
	public boolean start(String path, OnCompletionListener listener) {

		if (isPlaying) {
			System.out.println("已经在播放了");
			return false;
		}

		System.out.println("path:" + path);
		File file = new File(path);
		if (file.exists()) {
			System.out.println("存在文件");
		} else {
			System.out.println("没有文件");
		}

		stop();
		this.listener = listener;
		boolean flag = initAudioPlayer(path);

		if (flag) {
			isPlaying = true;
			return true;
		}
		return false;
	}

	/**
	 * 初始化
	 * 
	 * @param path
	 * @return
	 */
	private boolean initAudioPlayer(String path) {

		mPlayer = new MediaPlayer();
		mPlayer.reset();
		mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
		try {
			mPlayer.setDataSource(path);
			mPlayer.prepareAsync(); // mPlayer.prepare()
			mPlayer.setOnPreparedListener(this);

		} catch (Exception e) {
			e.printStackTrace();

			System.out.println("录音文件异常");
			return false;
		}
		return true;
	}

	@Override
	public void onPrepared(MediaPlayer mp) {
		mPlayer.start();
		mPlayer.setOnCompletionListener(listener);
		mPlayer.setOnErrorListener(new OnErrorListener() {

			@Override
			public boolean onError(MediaPlayer mp, int what, int extra) {
				System.out.println("setOnErrorListener");
				return false;
			}
		});
	}

	/**
	 * 获取播放时长
	 * 
	 * @param path
	 * @return ms
	 */
	public int getPlayerDuration(String path) {

		stop();
		if (initAudioPlayer(path)) {
			return mPlayer.getDuration();
		} else {
			System.out.println("播放时长获取失败");
			return 0;
		}
	}

	/**
	 * 停止播放
	 * 
	 * @return
	 */
	public void pause() {
		if (mPlayer != null) {
			mPlayer.pause();
		}
		isPlaying = false;
	}

	/**
	 * 停止播放
	 * 
	 * @return
	 */
	public boolean stop() {
		if (mPlayer != null) {
			mPlayer.stop();
			mPlayer.release();
			mPlayer = null;
		}
		isPlaying = false;
		return true;
	}

}
